package cn.xuqiudong.console.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.sql.DataSource;

/**
 * 描述: 数据库配置爱
 * @author Vic.xu
 * @since 2022-08-29 9:36
 */
@Configuration
public class DataSourceConfig {

    private final Logger logger = LoggerFactory.getLogger(DataSourceConfig.class);

    private static final String SECOND_DATA_SOURCE_NAME = "secondDataSource";

    /**
     * 默认的dataSource
     * @return DataSource
     */
    @Bean
    @Primary
    @ConfigurationProperties(value = "spring.datasource")
    public DataSource dataSource() {
        logger.info("create default DataSource");
        return DataSourceBuilder.create().build();
    }

    /**
     * 默认的JdbcTemplate
     * @return JdbcTemplate
     */
    @Bean
    @Primary
    public JdbcTemplate jdbcTemplate(DataSource dataSource) {
        logger.info("create default JdbcTemplate");
        return new JdbcTemplate(dataSource);
    }

    /**
     * 第二个数据源
     * @return DataSource
     */
    @Bean(name = SECOND_DATA_SOURCE_NAME)
    @ConfigurationProperties(value = "spring.datasource.second")
    public DataSource secondDataSource() {
        logger.info("create secondDataSource");
        return DataSourceBuilder.create().build();
    }

    /**
     * 第二个JdbcTemplate
     * @param dataSource SECOND_DATA_SOURCE_NAME
     * @return JdbcTemplate
     */
    @Bean
    public JdbcTemplate secondJdbcTemplate(@Qualifier(SECOND_DATA_SOURCE_NAME) DataSource dataSource) {
        logger.info("create secondJdbcTemplate");
        return new JdbcTemplate(dataSource);
    }
}
